package kr.hkit.masan_alarm;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import kr.hkit.masan_alarm.wheel.NumericWheelAdapter;
import kr.hkit.masan_alarm.wheel.OnWheelChangedListener;
import kr.hkit.masan_alarm.wheel.OnWheelScrollListener;
import kr.hkit.masan_alarm.wheel.WheelView;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class Masan_set extends Activity {
	private String strRingTone = "";
	private AlarmManager mManager = null;
	private TimePicker mTime;
	public Calendar calendar;
	private int mVibrate = 0;
	private TextView sTime;
	private SpannableStringBuilder ssb;
	
	// Time changed flag
	private boolean timeChanged = false;
	//
	private boolean timeScrolled = false;

	private int mAlarmHour = 12;
	private int mAlarmMinute = 0;
	// private GregorianCalendar mCalendar;
	
	private long db_id = -1;

	private NotificationManager mNotification;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		calendar = Calendar.getInstance();

		mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

		setContentView(R.layout.masan_set);

		final WheelView hours = (WheelView) findViewById(R.id.hour);
		hours.setAdapter(new NumericWheelAdapter(0, 23));
		hours.setLabel("hours");
		hours.setCyclic(true);

		final WheelView mins = (WheelView) findViewById(R.id.mins);
		mins.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
		mins.setLabel("mins");
		mins.setCyclic(true);

		((TextView) findViewById(R.id.ringtone))
				.setOnClickListener(ringSelectBtnListener);
		
		
		Button button = (Button) findViewById(R.id.set);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setAlarm();
			}
		});
		
		mTime = (TimePicker) findViewById(R.id.time_picker);
		// mTime.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
		// mTime.setCurrentMinute(calendar.get(Calendar.MINUTE));
		int curHours = calendar.get(Calendar.HOUR_OF_DAY);
		int curMinutes = calendar.get(Calendar.MINUTE);
		hours.setCurrentItem(curHours);
		mins.setCurrentItem(curMinutes);

		AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT
				|| mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) { 
			int maxVolume = mAudioManager
					.getStreamMaxVolume(AudioManager.STREAM_RING);
			mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume,
					0);
		}


		// add listeners
		addChangingListener(mins, "min");
		addChangingListener(hours, "hour");

		OnWheelChangedListener wheelListener = new OnWheelChangedListener() {

			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				if (!timeScrolled) {
					timeChanged = true;
					mTime.setCurrentHour(hours.getCurrentItem());
					mTime.setCurrentMinute(mins.getCurrentItem());
					timeChanged = false;
				}
			}
		};

		hours.addChangingListener(wheelListener);
		mins.addChangingListener(wheelListener);

		OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

			public void onScrollingStarted(WheelView wheel) {
				timeScrolled = true;
			}

			public void onScrollingFinished(WheelView wheel) {
				timeScrolled = false;
				timeChanged = true;
				mTime.setCurrentHour(hours.getCurrentItem());
				mTime.setCurrentMinute(mins.getCurrentItem());
				timeChanged = false;
			}
		};

		hours.addScrollingListener(scrollListener);
		mins.addScrollingListener(scrollListener);

		db_id = getIntent().getLongExtra("id", -1);
		if (db_id != -1) {
			mAlarmHour = getIntent().getIntExtra("hour", 12);
			mAlarmMinute = getIntent().getIntExtra("min", 33);
			mVibrate = getIntent().getIntExtra("vib", 0);
			strRingTone = getIntent().getStringExtra("ring");
			int day = getIntent().getIntExtra("day", 0);

			hours.setCurrentItem(mAlarmHour);
			mins.setCurrentItem(mAlarmMinute);

			if (mVibrate == 0) {
				((CheckBox) findViewById(R.id.alarm_set_vibrate))
						.setChecked(false);
			} else {
				((CheckBox) findViewById(R.id.alarm_set_vibrate))
						.setChecked(true);
			}
			// ring tone
			if (strRingTone != null) {
				showRingTone(Uri.parse(strRingTone));
			}
			if ((day & 0x0001) == 0x0001)
				((CheckBox) findViewById(R.id.sun)).setChecked(true);
			if ((day & 0x0002) == 0x0002)
				((CheckBox) findViewById(R.id.mon)).setChecked(true);
			if ((day & 0x0004) == 0x0004)
				((CheckBox) findViewById(R.id.tue)).setChecked(true);
			if ((day & 0x0008) == 0x0008)
				((CheckBox) findViewById(R.id.wed)).setChecked(true);
			if ((day & 0x0010) == 0x0010)
				((CheckBox) findViewById(R.id.thur)).setChecked(true);
			if ((day & 0x0020) == 0x0020)
				((CheckBox) findViewById(R.id.fri)).setChecked(true);
			if ((day & 0x0040) == 0x0040)
				((CheckBox) findViewById(R.id.sat)).setChecked(true);

		}
	}


	
	private void setAlarm() {
		if (((CheckBox) findViewById(R.id.alarm_set_vibrate)).isChecked()) {
			mVibrate = 1;
		} else {
			mVibrate = 0;
		}
		
		int apday = 0;

		if (((CheckBox) findViewById(R.id.sun)).isChecked()) {
			apday |= 0x0001;
		}
		if (((CheckBox) findViewById(R.id.mon)).isChecked()) {
			apday |= 0x0002;
		}
		if (((CheckBox) findViewById(R.id.tue)).isChecked()) {
			apday |= 0x0004;
		}
		if (((CheckBox) findViewById(R.id.wed)).isChecked()) {
			apday |= 0x0008;
		}
		if (((CheckBox) findViewById(R.id.thur)).isChecked()) {
			apday |= 0x0010;
		}
		if (((CheckBox) findViewById(R.id.fri)).isChecked()) {
			apday |= 0x0020;
		}
		if (((CheckBox) findViewById(R.id.sat)).isChecked()) {
			apday |= 0x0040;
		}

		if (apday == 0) {
			Toast.makeText(getBaseContext(), "반복요일을 설정하세요", Toast.LENGTH_LONG).show();
			return;
		}

		mAlarmHour = mTime.getCurrentHour();
		mAlarmMinute = mTime.getCurrentMinute();

		// db
		DB_Manager db = new DB_Manager(Masan_set.this);
		db.open();
		// db id -1
		if (db_id == -1) {
			db.addAlarm(1, apday, mAlarmHour, mAlarmMinute, mVibrate,
					strRingTone);
		} else {
			db.modifyAlarm(db_id, 1, apday, mAlarmHour, mAlarmMinute, mVibrate,
					strRingTone);
		}
		db.close();
 
		// //////////////////////////////////////
		Masan_info.startFirstAlarm(this);
		finish();
	}
	
	

	// Ringtone Manager
	private OnClickListener ringSelectBtnListener = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
			intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
					RingtoneManager.TYPE_ALL);
			startActivityForResult(intent, 123);
		}
	};

	// ringtone manager
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 123 && resultCode == RESULT_OK) {
			Uri uri = data
					.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
			if (uri != null) {
				strRingTone = uri.toString();
				showRingTone(uri);
			}
		}
	}

	
	private void showRingTone(Uri uri) {
		Ringtone ringtone = RingtoneManager.getRingtone(this, uri);
		if (ringtone != null) {
			String value = "알람음" + "\n" + ringtone.getTitle(this);
			ssb = new SpannableStringBuilder();
			ssb.append(value);
			ssb.setSpan(new ForegroundColorSpan(0xFFf4A460), 3, ssb.length(),
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			((TextView) findViewById(R.id.ringtone)).setText(ssb);
		} 
	}

	
	private void addChangingListener(final WheelView wheel, final String label) {
		wheel.addChangingListener(new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				wheel.setLabel(newValue != 1 ? label + "s" : label);
			}
		});
	}

}
